package com.android.xunxian.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.xunxian.adapter.UpdateFileAdater;
import com.android.xunxian.entry.JLTable;
import com.android.xunxian.utils.UConstants;
import com.android.xunxian.utils.Util;
import com.google.gson.Gson;
import com.oa.android.MyApplication;
import com.oa.android.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by zouqh on 2016/8/8.
 */
public class UpdateFileActivity extends Activity implements View.OnClickListener{

    @InjectView(R.id.close)
    ImageView close;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.ritgh_icon)
    ImageView ritghIcon;
    @InjectView(R.id.ritgh_text)
    TextView ritghText;
    @InjectView(R.id.upBtn)
    TextView upBtn;
    @InjectView(R.id.listview)
    ListView listview;
    UpdateFileAdater adater;
    private List<JLTable> jlTableList;

    private List<JLTable> upList;
    String name;
    private String id;
    private Dialog Jdialog;

    public static String path;

    private List<Boolean> flag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_file_activity);
        ButterKnife.inject(this);
        name=getIntent().getStringExtra("name");
        id=getIntent().getStringExtra("id");
        ritghText.setText("全选");
        if (null!=name){
            titleText.setText(name);
        }
        jlTableList=new ArrayList<>();
        upList=new ArrayList<>();
        flag=new ArrayList<>();
        close.setOnClickListener(this);
        ritghText.setOnClickListener(this);
        upBtn.setOnClickListener(this);
        path = Environment.getExternalStorageDirectory().getPath()
                + File.separator + "Xunxian" + File.separator + id + File.separator;
        try {
            List<JLTable> list = MyApplication.dbManager.selector(JLTable.class).where("id","=",id).findAll();
            if (list!=null&&list.size()>0){
                for (int i=0;i<list.size();i++){
                    String str=list.get(i).getFileName();
                    if (new File(path+str).exists()){
                        jlTableList.add(list.get(i));
                        flag.add(false);
                    }
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }

            if (jlTableList.size()>0){
                ritghText.setVisibility(View.VISIBLE);
                upBtn.setVisibility(View.VISIBLE);


        }

        adater=new UpdateFileAdater(this,jlTableList,flag);
        listview.setAdapter(adater);
        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                pointDialog("确定删除该文件吗？", position);
                return true;
            }
        });

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CheckBox checkBox= (CheckBox) view.findViewById(R.id.checkbox);
                checkBox.toggle();
                if (checkBox.isChecked()){
                    flag.set(position,true);
                }else{
                    flag.set(position,false);
                }
               System.out.println(flag);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.close:
                finish();
                break;

            case R.id.ritgh_text:
                for (int i=0;i<flag.size();i++){
                    flag.set(i,true);
                }
                adater.notifyDataSetChanged();
                break;

            case R.id.upBtn:
                upDate();
                break;
        }
    }


    /**
     * 提示
     */
    private void pointDialog(String str, final int p) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.exti_dialog_x,
                null);
        // 对话框
        Jdialog = new Dialog(this);
        Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Jdialog.show();

        Jdialog.setContentView(layout);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
         EditText text = (EditText) layout.findViewById(R.id.text);
        text.setVisibility(View.GONE);
        dialogTitle.setText(str);
        sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//				ContextUtil.getInstance().finishApp();
                Jdialog.cancel();
               File file=new File(path+jlTableList.get(p).getFileName());
                WhereBuilder b = WhereBuilder.b();
                b.and("id","=",id); //构造修改的条件
                try {
                    MyApplication.dbManager.delete(JLTable.class,b);
                } catch (DbException e) {
                    e.printStackTrace();
                }
                if (file.exists()){
                    file.delete();
                }
                jlTableList.remove(p);
                flag.remove(p);
                adater.notifyDataSetChanged();
                if (jlTableList.size()<=0){
                    upBtn.setVisibility(View.GONE);
                    ritghText.setVisibility(View.GONE);
                }


            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Jdialog.dismiss();
            }
        });

    }

    ProgressDialog dialog;
    File[] files=null;
    List<String> filePath;
    //获取巡线列表
    private void upDate() {
        dialog = ProgressDialog.show(this, null, "上传中...", true, false);
//
        Log.i("jlTableList.size()====",jlTableList.size()+"");
        Log.i("flag.size()====",flag.size()+"");
        if (jlTableList.size()>0){
            filePath=new ArrayList<>();
            for (int i=0;i<flag.size();i++){
                if (flag.get(i)){
                    filePath.add(jlTableList.get(i).getFileName());
                    upList.add(jlTableList.get(i));
                }
            }
        }else{
            dialog.dismiss();
            Toast.makeText(x.app(), "没有上传文件！", Toast.LENGTH_SHORT).show();
            return;
        }
       if (upList.size()<=0){
           Toast.makeText(x.app(), "请选择上传文件！", Toast.LENGTH_SHORT).show();
           dialog.dismiss();
           return;
       }


        Gson gson = new Gson();
        String json1=gson.toJson(upList);//将更新数组
        System.out.println("upList---"+upList);
        String info  ="{\"success\":\"true\", \"total\":\""+upList.size()+"\",\"rows\":"+json1+"}";

        RequestParams params = new RequestParams(UConstants.XX_UPDATE);
//
        params.addBodyParameter("LKind","CBJ");
        params.addBodyParameter("EmpId",UConstants.EmpId);
        params.addBodyParameter("PartId", UConstants.PartId );
        params.addBodyParameter("FileInfo",info);
       for (int j=0;j<filePath.size();j++){
           params.addBodyParameter("FILES", new File(path+filePath.get(j)));
       }


        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
//                        allPage = Integer.parseInt(object.getString("total"));
//                        allPage = (int) Math.ceil((double) allPage / pageSize);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Toast.makeText(x.app(), "上传成功！", Toast.LENGTH_SHORT).show();
                            for (int i =0;i<filePath.size();i++){
                                new File(path+filePath.get(i)).delete();
                                WhereBuilder b = WhereBuilder.b();
                                b.and("FileName","=",filePath.get(i)); //构造修改的条件
                                try {
                                    MyApplication.dbManager.delete(JLTable.class,b);
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                            }
                            try {
//                                MyApplication.dbManager.delete(JWdu.class);
                                List<JLTable> list = MyApplication.dbManager.selector(JLTable.class).where("id","=",id).findAll();
                                jlTableList.clear();
                                flag.clear();
                                upList.clear();
                                if (list!=null&&list.size()>0){
                                    jlTableList.addAll(list);
                                    for (int i=0;i<list.size();i++){
                                        flag.add(false);
                                    }

                                }else{
                                    upBtn.setVisibility(View.GONE);
                                    ritghText.setVisibility(View.GONE);
                                }
                                adater.notifyDataSetChanged();
                            } catch (DbException e) {
                                e.printStackTrace();
                            }



                        } else {
                            Toast.makeText(x.app(), "上传失败！", Toast.LENGTH_SHORT).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "连接失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }
}
